﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace Openlab.Tools.CodeGender
{
    /// <summary>
    /// 存储过程
    /// </summary>
    public abstract class StoredProcedure
    {
        /// <summary>
        /// 存储过程名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 作者
        /// </summary>
        public string Author { get; set; }

        /// <summary>
        /// 存储过程描述
        /// </summary>
        public string Description { get; set; }

        /// <summary>
        /// 存储过程参数
        /// </summary>
        public List<StoredProcedureParameter> Parameters { get; set; }

        public StoredProcedure(string name, string author)
        {
            this.Name = name;
            this.Author = author;
        }

        public bool HasParameter
        {
            get {
                return Parameters != null && Parameters.Count > 0;
            }
        }

        /// <summary>
        /// 存储过程内容
        /// </summary>
        public abstract string Body { get; }

        public string Sql {
            get {
                StringBuilder sql = new StringBuilder();
                sql.AppendLine("-- =============================================");
                sql.AppendLineFormat("-- Author:      {0}", Author);
                sql.AppendLineFormat("-- Create date:       {0}", DateTime.Now.ToString("yyyy-MM-dd"));
                sql.AppendLineFormat("-- Description:		{0}", Description);
                sql.AppendLine("-- =============================================");
                sql.AppendLineFormat("CREATE PROCEDURE {0}", Name);
                if (HasParameter)
                {
                    sql.AppendLine("(");
                    bool first = true;
                    foreach (StoredProcedureParameter param in Parameters)
                    {
                        sql.Append("\t");
                        if (!first)
                            sql.Append(",");
                        else
                            first = false;
                        sql.AppendLine(param.Sql);
                    }
                    sql.AppendLine(")");
                }
                sql.AppendLine("AS");
                sql.AppendLine("BEGIN");

                sql.AppendLine();
                sql.AppendLine(Body.IncreaseIndent(1));
                sql.AppendLine();

                sql.AppendLine("END");
                sql.AppendLine("GO");
                return sql.ToString();
            }
        }
    }
}
